import java.io.IOException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.LinkedList;

/**
 * Event-based proxy server
 * @author hussein
 */
public class EventServer {

    private ServerSocket server;
    private boolean running;
    private HashMapCache<URL, byte[]> cache;
    private final LinkedList<EventConnection> connectionList;

    public EventServer(int port, boolean hasCache) throws IOException {
        server = new ServerSocket(port);
        cache = new HashMapCache<URL, byte[]>(100, hasCache);
        connectionList = new LinkedList<EventConnection>();
        System.out.println(hasCache);
    }

    public void startServer() {
        createEventDispatchers();
        running = true;

        while (running) {
            acceptConnection();
        }
    }

    private void createEventDispatchers() {
        EventDispatcher ed = new EventDispatcher(cache, connectionList);
        ed.start();
    }

    private void acceptConnection() {
        try {
            EventConnection client = new EventConnection(server.accept());
            client.state = EventConnection.STATE.REQ;
            synchronized (connectionList) {
                connectionList.addLast(client);
                connectionList.notify();
            }
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
}
